# python rabbitmq 消化者
# exchange:autotest
# routing_key:api_report
# queue:api_report_queue

import pika
import json
from apps.autotest.business.monkey import MonkeyBusiness
import logging.config

# 日志
# 按照日期轮训

config = {
    'exchange': 'autotest',
    'routing_key': 'api_report',
    'queue': 'api_report_queue',
}

dictConfig = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'master_format': {
            'class': 'logging.Formatter',
            'format': '%(asctime)s [%(name)s] [%(levelname)s] %(filename)s - %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S'
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': logging.DEBUG,
            'formatter': 'master_format',
        },
        'reportFileHandler': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': './logs/mq/report.log',
            'level': logging.INFO,
            'formatter': 'master_format',
            'interval': 1,
            'when': 'D'
        },
    },
    'loggers': {
        'reportLogger': {
            'handlers': ['console', 'reportFileHandler'],
            'level': 'INFO'
        }
    }
}

logging.config.dictConfig(dictConfig)
log = logging.getLogger(name='reportLogger')

credentials = pika.PlainCredentials('autotest', '123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
            host = '127.0.0.1', port = '5672', virtual_host = 'autotest', credentials = credentials))
channel = connection.channel()
channel.exchange_declare(config['exchange'], 'direct')
channel.queue_declare(queue = config['queue'])
channel.queue_bind(exchange = config['exchange'], queue = config['queue'], routing_key = config['routing_key'])

def callback(ch, method, properties, body):
    data = json.loads(body.decode())
    code, msg = MonkeyBusiness.get_report_html(report_url = data['report_url'], task_id = data['task_id'])

    if code == 0:
        log.info('[下载日志成功] {}'.format(data))
    else:
        log.warning('[{}] {}'.format(msg, data))

    ch.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_consume(config['queue'], callback, False)

channel.start_consuming()
